<template>
  <div class="main">
    <a-form
      id="formLogin"
      ref="formLogin"
      :form="form"
      class="user-layout-login"
      @submit="handleSubmit"
    >
      <div class="change_tab">
        <span :class="tableIndex===0?'current':''" style="margin-left:79px;" @click="handleTabClick(0)">账号密码登录</span>
        <span :class="tableIndex===1?'current':''" style="margin-left:60px" @click="handleTabClick(1)">手机号登录</span>
      </div>
      <div v-if="tableIndex===0">
        <a-alert
          v-if="isLoginError"
          :message="this.accountLoginErrMsg"
          showIcon
          style="margin-bottom: 12px;"
          type="error" />

        <a-form-item style="margin-top: 12px">
          <a-input
            v-decorator="[
              'account',
              { initialValue:'superAdmin', rules: [{ required: true, message: '请输入帐户名' }, { validator: handleUsernameOrEmail }], validateTrigger: 'change'}
            ]"
            class="login-input"
            placeholder="账号"
            size="large"
            type="text"
          >
            <icon-font slot="prefix" :style="{ 'font-size':'20px'}" type="icon-zhanghu"></icon-font>
          </a-input>
        </a-form-item>

        <a-form-item style="margin-top: 12px">
          <a-input
            v-decorator="[
              'password',
              { initialValue:'123456', rules: [{ required: true, message: '请输入密码' }], validateTrigger: 'blur'}
            ]"
            autocomplete="false"
            placeholder="密码"
            size="large"
            type="password"
          >
            <icon-font slot="prefix" :style="{ 'font-size':'20px'}" type="icon-mima"></icon-font>
          </a-input>
        </a-form-item>
      </div>
      <div v-else>
        <a-alert
          v-if="isLoginError"
          :message="this.accountLoginErrMsg"
          showIcon
          style="margin-bottom: 12px;"
          type="error" />
        <a-form-item style="margin-top: 12px">
          <a-input
            v-decorator="['mobile', {rules: [{ required: true, pattern: /^1[34578]\d{9}$/, message: '请输入正确的手机号' }], validateTrigger: 'change'}]"
            placeholder="手机号"
            size="large"
            type="text">
            <a-icon slot="prefix" :style="{ color: 'rgba(0,0,0,255)' }" type="mobile" />
          </a-input>
        </a-form-item>

        <a-row :gutter="14" style="margin-top: 12px">
          <a-col :span="14" class="gutter-row">
            <a-form-item>
              <a-input
                v-decorator="['captcha', {rules: [{ required: true, message: '请输入验证码' }], validateTrigger: 'blur'}]"
                placeholder="验证码"
                size="large"
                type="text">
                <a-icon slot="prefix" :style="{ color: 'rgba(0,0,0,255)' }" type="mail" />
              </a-input>
            </a-form-item>
          </a-col>
          <a-col :span="10" class="gutter-row">
            <a-button
              :disabled="state.smsSendBtn"
              class="getCaptcha"
              size="large"
              tabindex="-1"
              v-text="!state.smsSendBtn && '获取验证码' || (state.time+' s')"
              @click.stop.prevent="getCaptcha"
            ></a-button>
          </a-col>
        </a-row>
      </div>

      <a-form-item>
        <a-checkbox v-decorator="['rememberMe', { valuePropName: 'checked' }]" style="color:#5D5D5D;">自动登录</a-checkbox>
        <span class="forge-password">忘记密码 | 注册</span>
      </a-form-item>
      <a-form-item>
        <Verify
          ref="verify"
          :captchaType="'clickWord'"
          :imgSize="{ width: '330px', height: '155px' }"
          :mode="'pop'"
          @success="verifySuccess"
        ></Verify>
      </a-form-item>
      <a-form-item>
        <a-config-provider :auto-insert-space-in-button="false">
          <a-button
            :disabled="state.loginBtn"
            :loading="state.loginBtn"
            class="login-button"
            htmlType="submit"
            size="large"
            type="primary"
          >登录
          </a-button>
        </a-config-provider>
      </a-form-item>
    </a-form>

    <two-step-captcha
      v-if="requiredTwoStepCaptcha"
      :visible="stepCaptchaVisible"
      @cancel="stepCaptchaCancel"
      @success="stepCaptchaSuccess"
    ></two-step-captcha>
  </div>
</template>

<script>
import TwoStepCaptcha from '@/components/tools/TwoStepCaptcha'
import { mapActions } from 'vuex'
import { getCaptchaOpen, getSmsCaptcha } from '@/api/modular/system/loginManage'
import Verify from '@/components/verifition/Verify'

export default {
  components: {
    TwoStepCaptcha,
    Verify
  },
  data() {
    return {
      loginBtn: false,
      // login type: 0 email, 1 username, 2 telephone
      loginType: 0,
      isLoginError: false,
      requiredTwoStepCaptcha: false,
      stepCaptchaVisible: false,
      tableIndex: 0,
      form: this.$form.createForm(this),
      state: {
        time: 60,
        loginBtn: false,
        // login type: 0 email, 1 username, 2 telephone
        loginType: 0,
        smsSendBtn: false
      },
      accountLoginErrMsg: '',
      tenantOpen: false,
      captchaOpen: false, // 是否开启验证码
      tenantsList: [],
      loginParams: [] // 登录参数

    }
  },
  created() {
    this.getCaptchaOpen()
  },
  methods: {
    ...mapActions(['Login', 'Logout', 'dictTypeData']),
    /**
     * 获取验证码开关
     */
    getCaptchaOpen() {
      getCaptchaOpen().then((res) => {
        if (res.success) {
          this.captchaOpen = res.data
        }
      })
    },
    // handler
    handleUsernameOrEmail(rule, value, callback) {
      const { state } = this
      const regex = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+((\.[a-zA-Z0-9_-]{2,3}){1,2})$/
      if (regex.test(value)) {
        state.loginType = 0
      } else {
        state.loginType = 1
      }
      callback()
    },
    handleTabClick(index) {
      if (this.tableIndex === index) {
        return
      }
      this.isLoginError = false
      this.tableIndex = index
    },
    handleSubmit(e) {
      e.preventDefault()
      const {
        form: { validateFields },
        state,
        tableIndex,
        Login
      } = this

      state.loginBtn = true
      const validateFieldsKey = tableIndex === 0 ? ['account', 'password'] : ['mobile', 'captcha']
      if (this.tenantOpen) {
        validateFieldsKey.push('tenantCode')
      }
      validateFields(validateFieldsKey, { force: true }, (err, values) => {
        this.loginParams = values
        if (!err) {
          // 是否开启验证码
          if (this.captchaOpen) {
            this.$refs.verify.show()
            state.loginBtn = false
            return
          }
          const loginParams = { ...values }
          delete loginParams.account
          loginParams[!state.loginType ? 'email' : 'account'] = values.account
          loginParams.password = values.password
          if (this.tenantOpen) {
            loginParams.tenantCode = values.tenantCode
          }
          Login(loginParams)
            .then((res) => this.loginSuccess(res))
            .catch(err => this.requestFailed(err))
            .finally(() => {
              state.loginBtn = false
            })
        } else {
          setTimeout(() => {
            state.loginBtn = false
          }, 600)
        }
      })
    },
    /**
     * 获取验证码
     */
    verifySuccess(params) {
      this.loginParams.code = params.captchaVerification
      this.Login(this.loginParams).then((res) => this.loginSuccess(res))
        .catch(err => this.requestFailed(err))
        .finally(() => {
          this.state.loginBtn = false
        })
    },
    getCaptcha(e) {
      e.preventDefault()
      const { form: { validateFields }, state } = this

      validateFields(['mobile'], { force: true }, (err, values) => {
        if (!err) {
          state.smsSendBtn = true

          const interval = window.setInterval(() => {
            if (state.time-- <= 0) {
              state.time = 60
              state.smsSendBtn = false
              window.clearInterval(interval)
            }
          }, 1000)

          const hide = this.$message.loading('验证码发送中..', 0)
          getSmsCaptcha({ mobile: values.mobile }).then(res => {
            setTimeout(hide, 2500)
            this.$notification['success']({
              message: '提示',
              description: '验证码获取成功，您的验证码为：' + res.result.captcha,
              duration: 8
            })
          }).catch(err => {
            setTimeout(hide, 1)
            clearInterval(interval)
            state.time = 60
            state.smsSendBtn = false
            this.requestFailed(err)
          })
        }
      })
    },
    stepCaptchaSuccess() {
      this.loginSuccess()
    },
    stepCaptchaCancel() {
      this.Logout().then(() => {
        this.loginBtn = false
        this.stepCaptchaVisible = false
      })
    },
    loginSuccess(res) {
      this.$router.push({ path: '/' })
      this.$store.dispatch('ToggleFixedMargin', '0')
      this.isLoginError = false
      // 加载字典所有字典到缓存中
      this.dictTypeData().then((res) => {
      })
    },
    requestFailed(err) {
      // this.accountLoginErrMsg = err
      // this.isLoginError = true
      this.$message.error(err)
    }
  }
}
</script>

<style lang="less" scoped>

@font-face {
  font-family: "Microsoft YaHei";
}

.change_tab {
  margin-top: 40px;
  margin-bottom: 22px;
}

.change_tab span {
  display: inline-block;
  color: #1890FF;
  margin: 0;
  padding: 0;
  cursor: pointer;
  font-size: 14px;
}

.change_tab span.current {
  border-bottom: 2px solid #1890FF
}

.user-layout-login {

  label {
    font-size: 14px;
  }

  .getCaptcha {
    font-size: 14px;
  }

  .forge-password {
    font-size: 14px;
    color: #C4C4C4;
    float: right;
    margin-right: 5px;
  }

  .user_register {
    font-size: 14px;
    color: #C4C4C4;
  }

  button.login-button {
    border-radius: 3px;
    font-size: 14px;
    width: 100%;
    margin-top: 5.5px;
  }
}
</style>
